package io.hellsinger.vortex.ui.component.item.title

import android.content.Context
import android.view.View.MeasureSpec.AT_MOST
import android.view.View.MeasureSpec.EXACTLY
import android.view.View.MeasureSpec.getMode
import android.view.View.MeasureSpec.getSize
import android.view.View.MeasureSpec.makeMeasureSpec
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import io.hellsinger.vortex.ui.component.adapter.holder.RecyclableView
import io.hellsinger.vortex.ui.component.contains
import io.hellsinger.vortex.ui.component.dp
import io.hellsinger.vortex.ui.dsl.text
import kotlin.math.min

class TitleItemView(
    context: Context,
) : FrameLayout(context),
    RecyclableView<String> {
    private val innerWidthPadding = 16.dp

    private val desireWidth = MATCH_PARENT
    private val desireHeight = 48.dp

    private val title = text { textSize = 14F }

    private val containsTitle: Boolean
        get() = contains(title)

    fun setTitleAlignment(alignment: Int) {
        title.textAlignment = alignment
    }

    fun setTitleColor(color: Int) {
        title.setTextColor(color)
    }

    fun setTitleTextSize(size: Float) {
        title.textSize = size
    }

    fun setTitle(value: String? = null) {
        title.text = value
    }

    override fun onMeasure(
        widthMeasureSpec: Int,
        heightMeasureSpec: Int,
    ) {
        val widthSize = getSize(widthMeasureSpec)
        val widthMode = getMode(widthMeasureSpec)
        val heightSize = getSize(heightMeasureSpec)
        val heightMode = getMode(heightMeasureSpec)

        val width =
            when (widthMode) {
                EXACTLY -> widthSize
                AT_MOST -> widthSize
                else -> desireWidth
            } + paddingRight + paddingLeft

        val height =
            when (heightMode) {
                EXACTLY -> heightSize
                AT_MOST -> min(desireHeight, heightSize)
                else -> desireHeight
            } + paddingTop + paddingBottom

        setMeasuredDimension(width, height)

        val availableWidth = width - innerWidthPadding
        if (containsTitle) {
            title.measure(makeMeasureSpec(availableWidth, EXACTLY), makeMeasureSpec(24.dp, EXACTLY))
        }
    }

    override fun onLayout(
        changed: Boolean,
        left: Int,
        top: Int,
        right: Int,
        bottom: Int,
    ) {
        var layoutWidth = innerWidthPadding

        if (containsTitle) {
            title.layout(
                layoutWidth,
                (height - title.lineHeight) / 2,
                layoutWidth + title.measuredWidth - innerWidthPadding,
                (height - title.lineHeight) / 2 + title.lineHeight + 3.dp,
            )
            layoutWidth += title.measuredWidth - innerWidthPadding
        }
    }

    override fun onBind(item: String) {
        setTitle(item)
    }

    override fun onUnbind() {
        setTitle(null)
    }
}
